package cn.jluzh.blog.modules.article.controller;

import cn.jluzh.blog.commons.result.Result;
import cn.jluzh.blog.commons.result.ResultFactory;
import cn.jluzh.blog.modules.article.entity.SysArticle;
import cn.jluzh.blog.modules.article.entity.SysArticleArchives;
import cn.jluzh.blog.modules.article.service.impl.ArticleServiceImpl;
import cn.jluzh.blog.modules.article.service.impl.ArticleTagServiceImpl;
import cn.jluzh.blog.modules.category.service.impl.CategoryServiceImpl;
import cn.jluzh.blog.modules.security.eneity.SecurityUser;
import cn.jluzh.blog.modules.tag.service.impl.TagServiceImpl;
import cn.jluzh.blog.modules.user.entity.SysUser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: hjc
 **/

@RestController
@Api(tags = "文章相关接口")
@RequestMapping("article")
public class ArticleController {

    public static final int HOT_OR_NEW_ARTICLE_NUM = 6;
    public static final int ARTICLE_ARCHIVE_LIMIT_NUM = 8;

    @Autowired
    ArticleServiceImpl articleService;
    @Autowired
    TagServiceImpl tagService;
    @Autowired
    CategoryServiceImpl categoryService;
    @Autowired
    ArticleTagServiceImpl articleTagService;

    @GetMapping("getAllArticle")
    @ApiOperation("查询所有的文章")
    public Result getAllArticle( @RequestParam(name="pageNo",defaultValue="1") Integer pageNo,
                                 @RequestParam(name="pageSize",defaultValue="10") Integer pageSize,
                                 @RequestParam(name="tagId",required = false) Integer tagId,
                                 @RequestParam(name = "categoryId",required = false) Integer categoryId,
                                 @RequestParam(name = "year",required = false)String year,
                                 @RequestParam(name = "month",required = false)String month,
                                 @RequestParam(name="query", required=false) String query
                                 ){
        PageHelper.startPage(pageNo, pageSize);
        List<SysArticle> allArticle;
        if (categoryId!=null){
            allArticle = articleService.getArtByCateId(categoryId);
        }
        else if (tagId!=null){
            allArticle = articleService.getArtByTagId(tagId);
        }else if(StringUtils.isNotBlank(year)&&StringUtils.isNotBlank(month)){
            allArticle=articleService.getArtByDate(year,month);
        }else if(query!=null){
            allArticle=articleService.getAllArticleByTitle(query);
        }
        else {
            allArticle = articleService.getAllArticle();
        }
        if(CollectionUtils.isEmpty(allArticle)){
            return ResultFactory.buildResult(200,"文章到底了!",null);
        }else {
            PageInfo<SysArticle> pageInfo = new PageInfo<>(allArticle);
            return ResultFactory.buildSuccessResult(pageInfo);
        }
    }

    @GetMapping("getArticleById")
    @ApiOperation("根据文章Id获取文章")
    public Result getArticleById(@RequestParam("id") Long id){
        SysArticle article = articleService.getById(id);
        return ResultFactory.buildSuccessResult(article);
    }
    /**
     * 编辑文章时：
     * 通过文章Id获取文章详情
     * 不需要用户信息
     */
    @GetMapping("/getUpdateArtById")
    public Result getUpdateArtById(@RequestParam("id") Long id) {
        SysArticle article = articleService.getById(id);
        JSONObject object = new JSONObject();
        object.put("id", article.getId());
        object.put("title", article.getTitle());
        object.put("summary", article.getSummary());
        object.put("content", article.getContent());

        object.put("category", categoryService.getById(article.getCategoryId()));

        object.put("tags", tagService.getTagByArtId(article.getId()));

        return ResultFactory.buildSuccessResult(object);
    }

    /**
     * 最热文章
     */
    @GetMapping("/hot")
    @ApiOperation("查询最热文章")
    public Result listHotArticles() {
        JSONArray array = getHotOrNewArticles("view_num");
        return ResultFactory.buildSuccessResult(array);
    }

    /**
     * 最新文章
     */
    @GetMapping("/new")
    @ApiOperation("查询最新文章")
    public Result listNewArticles() {
        JSONArray array = getHotOrNewArticles("create_time");
        return ResultFactory.buildSuccessResult(array);
    }

    /**
     * 获取最热或最新文章
     * type 可取 view_num 最热
     * create_time 最新
     *
     * @param type
     * @return
     */
    private JSONArray getHotOrNewArticles(String type) {
        Page<SysArticle> page = new Page<>(1, HOT_OR_NEW_ARTICLE_NUM);
        Page<SysArticle> pageList = articleService.page(page, new QueryWrapper< >());

        JSONArray array = new JSONArray();
        for (SysArticle article : pageList.getRecords()) {
            JSONObject object = new JSONObject();
            object.put("id", article.getId());
            object.put("title", article.getTitle());
            array.add(object);
        }
        return array;
    }

    @GetMapping("view")
    @ApiOperation("查看文章详情内容")
    public Result oneArticleInfoById(@RequestParam(name = "id") Long id) {
        JSONObject articleDetailAndAddViewNum = articleService.getArticleDetailAndAddViewNum(id);
        return ResultFactory.buildSuccessResult(articleDetailAndAddViewNum);
    }

    /**
     * 汇总查询
     */
    @GetMapping("/archives")
    @ApiOperation("获取归档信息")
    public Result archives() {
        List<SysArticleArchives> sysArticleArchives = articleService.queyArticleArchives(ARTICLE_ARCHIVE_LIMIT_NUM);
        return ResultFactory.buildSuccessResult(sysArticleArchives);
    }

    @PostMapping("addArticle")
    @ApiOperation("新增文章")
    public Result addArticle (@RequestBody SysArticle sysArticle){
        boolean b = articleService.saveOrUpdate(sysArticle);
        return ResultFactory.buildSuccessResult(b);
    }

    @DeleteMapping("deleteArticle")
    @ApiOperation("删除文章")
    public Result deleteArticle(@RequestParam(name = "id") Long id){
        boolean b = articleService.removeById(id);
        return ResultFactory.buildSuccessResult(b);
    }

    @PostMapping("updateArticle")
    @ApiOperation("修改文章信息")
    public Result updateCategory(@RequestBody SysArticle sysArticle){
        boolean b = articleService.updateById(sysArticle);
        return ResultFactory.buildSuccessResult(b);
    }

    /**
     * 文章编辑与新增
     */
    @PostMapping("/publishArticle")
    public Result publishArticle(@RequestBody JSONObject json) {
        SysUser user = SecurityUser.getUser();
        Long id = json.getLong("id");
        if (id != null) {
            //编辑文章
            SysArticle article = articleService.getById(id);
            if (article == null) {
                throw new RuntimeException("参数错误");
            }
            articleService.updateOneArticle(user, article, json);
        } else {
            //新增文章
            id = articleService.addOneArticle(user, json);
        }

        JSONObject object = new JSONObject();
        object.put("articleId", id);
        return ResultFactory.buildSuccessResult(object);
    }

    @GetMapping("/articleTotal")
    @ApiOperation("获取文章总量")
    public Result articleTotal() {
        int count = articleService.count();
        return ResultFactory.buildSuccessResult(count);
    }
}
